<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import request from '@/utils/axios'

interface Announcement {
    id: number
    title: string
    content: string
    type: number
    status: number
    createTime: string
    updateTime: string
    createBy: number | null
    updateBy: number | null
    remark: string | null
}

const tableData = ref<Announcement[]>([])
const loading = ref(false)
const total = ref(0)

const currentPage = ref(1)
const pageSize = ref(10)

const searchForm = ref({
    title: '',
    type: null,
    status: null
})

// 获取公告列表数据
const fetchAnnouncements = async () => {
    try {
        loading.value = true
        const params = {
            current: currentPage.value,
            size: pageSize.value,
            ...searchForm.value
        }
        const { data } = await request.get('/announcements/page', { params })
        tableData.value = data.data.records
        total.value = data.data.total
    } catch (error) {
        ElMessage.error('获取公告列表失败')
        console.error('获取公告列表失败：', error)
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    currentPage.value = 1
    fetchAnnouncements()
}

const handleReset = () => {
    searchForm.value = {
        title: '',
        type: null,
        status: null
    }
    currentPage.value = 1
    fetchAnnouncements()
}

// 监听分页变化
const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchAnnouncements()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchAnnouncements()
}

// 详情弹窗相关
const detailVisible = ref(false)
const currentAnnouncement = ref<Announcement>()

// 编辑弹窗相关
const editVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref<Announcement>({
    id: 0,
    title: '',
    content: '',
    type: 0,
    status: 1,
    createTime: '',
    updateTime: '',
    createBy: null,
    updateBy: null,
    remark: null
})

const rules = ref<FormRules>({
    title: [
        { required: true, message: '请输入公告标题', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    content: [
        { required: true, message: '请输入公告内容', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择公告类型', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ]
})

const handleViewDetail = (row: Announcement) => {
    currentAnnouncement.value = row
    detailVisible.value = true
}

const handleEdit = (row: Announcement) => {
    editForm.value = { ...row }
    editVisible.value = true
}

const handleDelete = async (row: Announcement) => {
    try {
        await request.delete(`/announcements/${row.id}`)
        ElMessage.success('删除成功')
        fetchAnnouncements()
    } catch (error) {
        ElMessage.error('删除失败')
        console.error('删除失败：', error)
    }
}

const handleEditSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            try {
                await request.put(`/announcements/${editForm.value.id}`, editForm.value)
                ElMessage.success('编辑成功')
                editVisible.value = false
                fetchAnnouncements()
            } catch (error) {
                ElMessage.error('编辑失败')
                console.error('编辑失败：', error)
            }
        }
    })
}

const addVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = ref({
    title: '',
    content: '',
    type: 0,
    status: 1,
    remark: ''
})

const handleAdd = () => {
    addVisible.value = true
}

const handleAddSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid) => {
        if (valid) {
            try {
                await request.post('/announcements/add', addForm.value)
                ElMessage.success('添加公告成功')
                addVisible.value = false
                fetchAnnouncements()
                // 重置表单
                addForm.value = {
                    title: '',
                    content: '',
                    type: 0,
                    status: 1,
                    remark: ''
                }
            } catch (error) {
                ElMessage.error('添加公告失败')
                console.error('添加公告失败：', error)
            }
        }
    })
}

onMounted(() => {
    fetchAnnouncements()
})
</script>

<template>
    <!-- 添加公告弹窗 -->
    <el-dialog v-model="addVisible" title="添加公告" width="50%" :before-close="() => addVisible = false">
        <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="addForm.title" placeholder="请输入公告标题" />
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input v-model="addForm.content" type="textarea" :rows="6" placeholder="请输入公告内容" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
                <el-select v-model="addForm.type" placeholder="请选择公告类型">
                    <el-option label="系统公告" :value="0" />
                    <el-option label="活动通知" :value="1" />
                    <el-option label="其他" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="addForm.status" placeholder="请选择状态">
                    <el-option label="启用" :value="1" />
                    <el-option label="禁用" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="addForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="addVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddSubmit(addFormRef)">保存</el-button>
        </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="公告详情" width="60%" :before-close="() => detailVisible = false">
        <el-descriptions :column="1" border>
            <el-descriptions-item label="标题">
                {{ currentAnnouncement?.title }}
            </el-descriptions-item>
            <el-descriptions-item label="内容">
                <div style="white-space: pre-wrap;">{{ currentAnnouncement?.content }}</div>
            </el-descriptions-item>
            <el-descriptions-item label="类型">
                {{ currentAnnouncement?.type === 0 ? '系统公告' : currentAnnouncement?.type === 1 ? '活动通知' : '其他' }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
                <el-tag :type="currentAnnouncement?.status === 1 ? 'success' : 'danger'" effect="dark">
                    {{ currentAnnouncement?.status === 1 ? '启用' : '禁用' }}
                </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
                {{ currentAnnouncement?.createTime }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
                {{ currentAnnouncement?.updateTime }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" v-if="currentAnnouncement?.remark">
                {{ currentAnnouncement?.remark }}
            </el-descriptions-item>
        </el-descriptions>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editVisible" title="编辑公告" width="50%" :before-close="() => editVisible = false">
        <el-form ref="editFormRef" :model="editForm" :rules="rules" label-width="80px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="editForm.title" />
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input v-model="editForm.content" type="textarea" :rows="6" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
                <el-select v-model="editForm.type" placeholder="请选择公告类型">
                    <el-option label="系统公告" :value="0" />
                    <el-option label="活动通知" :value="1" />
                    <el-option label="其他" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select v-model="editForm.status" placeholder="请选择状态">
                    <el-option label="启用" :value="1" />
                    <el-option label="禁用" :value="0" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="editForm.remark" type="textarea" :rows="3" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="editVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEditSubmit(editFormRef)">保存</el-button>
        </template>
    </el-dialog>

    <div class="announcements-container">
        <div class="header">
            <h2>公告管理</h2>
        </div>
        <div class="search-area">
            <div class="search-form">
                <el-form :inline="true" :model="searchForm">
                    <el-form-item label="标题">
                        <el-input v-model="searchForm.title" placeholder="请输入公告标题" clearable />
                    </el-form-item>
                    <el-form-item label="类型">
                        <el-select v-model="searchForm.type" placeholder="请选择公告类型" clearable>
                            <el-option label="系统公告" :value="0" />
                            <el-option label="活动通知" :value="1" />
                            <el-option label="其他" :value="2" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                            <el-option label="启用" :value="1" />
                            <el-option label="禁用" :value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="table-container">
            <div class="table-header">
                <el-button type="primary" @click="handleAdd">添加公告</el-button>
            </div>
            <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
                <el-table-column prop="id" label="ID" min-width="80" align="center" />
                <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
                <el-table-column prop="type" label="类型" min-width="120" align="center">
                    <template #default="{ row }">
                        {{ row.type === 0 ? '系统公告' : row.type === 1 ? '活动通知' : '其他' }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="120" align="center">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
                <el-table-column label="操作" min-width="200" align="center" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleViewDetail(row)">查看</el-button>
                        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container" style="margin-top: 20px; text-align: right;">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>
    </div>
</template>

<style scoped>
.announcements-container {
    padding: 20px;
}

.header {
    margin-bottom: 20px;
}

.search-area {
    margin-bottom: 20px;
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
    margin-bottom: 20px;
}
</style>